 ///
 /// @file    Mystring.cc
 /// @author  lemon(haohb13@gmail.com)
 /// @date    2023-04-25 09:51:25
 ///
 
#include <string.h>
#include <iostream>
using std::cout;
using std::endl;

//高频笔试题
class String
{
public:
	String()
	//: _pstr(nullptr)
	: _pstr(new char[1]())
	{	cout << "String()" << endl;	}

	String(const char *pstr)
	: _pstr(new char[strlen(pstr) + 1]())
	{
		strcpy(_pstr, pstr);
		cout << "String(const char*)" << endl;
	}

	String(const String &rhs)
	: _pstr(new char[strlen(rhs._pstr) + 1]())
	{
		strcpy(_pstr, rhs._pstr);
		cout << "String(const String&)" << endl;
	}

	String &operator=(const String &rhs)
	{
		if(this != &rhs) {
			delete [] _pstr;
			_pstr = new char[strlen(rhs._pstr) + 1]();
			strcpy(_pstr, rhs._pstr);
		}
		return *this;
	}

	~String()
	{
		delete [] _pstr;
		_pstr = nullptr;
		cout << "~String()" << endl;
	}

	void print() {
		//当用cout直接输出一个空指针,
		//并且该空指针的类型是char*
		//程序直接崩溃退出
		//没有任何提示
		if(_pstr) {
			cout << _pstr << endl;//cout的bug
		}
		//int * p = nullptr;
		//cout << "p:" << p << endl;
	}
    //size_t length() const;
    //const char * c_str() const;
private:
	char * _pstr;
};

 
void test0() 
{
	String s1;
	s1.print();

	String s2("hello,world");
	s2.print();

	String s3 = s2;
	s3.print();

	String s4("wangdao");
	cout << "s4:";
	s4.print();

	s4 = s3;
	cout << "s4:";
	s4.print();
} 
 
int main(void)
{
	test0();
	return 0;
}
